<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api;

use xsl\basic\BaseController;

class Upload extends BaseController
{
    public function file()
    {
    }

    public function image()
    {
        if ($this->request->file('image')->isValid()) {
            // 该路径为上传文件的临时路径
            $file = $this->request->file('image');
            $dir = BASE_PATH . '/public/uploads/' . date('Y-m-d', time());
            if (! is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            // 没有查询参数
//            $url = $this->request->url();
            // 外部访问地址
            // 获取当前请求的 URI 对象
//            $uri = $this->request->getUri();
//            $host = $uri->getHost();
//            $path = $host . '/uploads/' . date('Y-m-d', time()) . '/' . $file->getClientFilename();
            $path = 'http://127.0.0.1:90/uploads/' . date('Y-m-d', time()) . '/' . $file->getClientFilename();
            // 本地保存地址
            $temp = BASE_PATH . '/public/uploads/' . date('Y-m-d', time()) . '/' . $file->getClientFilename();
            $file->moveTo($temp);
            if ($file->isMoved()) {
                /*
                 * ext: "jpg"
                 * originalName: "2.jpg"
                 * path: "https://kaocha-api.nftcha.com/uploads/99/c611b3c3724608b5e461458fd68238.jpg"
                 * size: 119790
                 * type: "image"
                 */
                $data['ext'] = $file->getClientMediaType();
                $data['originalName'] = $file->getClientFilename();
                $data['path'] = $path;
                $data['size'] = $file->getSize();
                $data['type'] = 'image';
                return $this->success($data);
            }
        }
        return $this->error('上传失败');
    }
}
